package com.hpin.fansea.my;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.MyMessageAdapter;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.MyMessage;
import com.hpin.fansea.bean.MyMessageResult;
import com.hpin.fansea.pulltorefush.PullToRefreshBase;
import com.hpin.fansea.pulltorefush.PullToRefreshListView;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.widget.CircleImageView;
import com.lidroid.xutils.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 我的消息
 * Created by Aaron on 15/9/23.
 */
public class MessageActivity extends BaseActivity {

    private DisplayImageOptions options;
    private PullToRefreshListView plv_message;

    private int pageIndex = 0;
    private List<MyMessageResult.MyMessageDetail> myMessaglList = new ArrayList<MyMessageResult.MyMessageDetail>();
    private MyMessageAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_my_message);

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.icon_headpic_default)
                .showImageForEmptyUri(R.mipmap.icon_headpic_default)
                .showImageOnFail(R.mipmap.icon_headpic_default)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();

        initWidget();

        getMyMessageData();

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.my_news));

        iv_left.setOnClickListener(this);

        setHeadInfo();

        mAdapter = new MyMessageAdapter(this, myMessaglList);

        plv_message = (PullToRefreshListView) findViewById(R.id.plv_message);

        plv_message.setAdapter(mAdapter);

        plv_message.setMode(PullToRefreshBase.Mode.BOTH);

        plv_message.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(MessageActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                pageIndex = 0;
                myMessaglList.clear();
                getMyMessageData();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                String label = DateUtils.formatDateTime(MessageActivity.this, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                getMyMessageData();

            }
        });

    }

    private void setHeadInfo() {

        // 头像
        CircleImageView head_img = (CircleImageView) findViewById(R.id.head_img);

        ImageLoader.getInstance().displayImage(sp.getString(Constant.headPic, ""), head_img, options);

        // 认证的图片
        ImageView my_auth = (ImageView) findViewById(R.id.my_auth);
        TextView tv_username = (TextView) findViewById(R.id.tv_username);
        TextView tv_community = (TextView) findViewById(R.id.tv_community);

        if (Constant.AUTH_USER.equals(sp.getString(Constant.status, "")) || Constant.AUTH_PASSED.equals(sp.getString(Constant.status, "")))
            my_auth.setVisibility(View.VISIBLE);
        else
            my_auth.setVisibility(View.INVISIBLE);

        tv_username.setText(sp.getString(Constant.nickname, ""));
        tv_community.setText(sp.getString(Constant.communityName, ""));

    }

    /**
     * 获取我的消息
     */
    private void getMyMessageData() {

        MyMessage myMessage = new MyMessage();
        myMessage.lat = "";
        myMessage.lng="";
        myMessage.pageIndex = (++pageIndex) + "";
        myMessage.pageSize = Constant.PAGECOUNT+"";
        myMessage.token= sp.getString(Constant.token, "");
        myMessage.systemType= Constant.SYSTEM_TYPE;

        String jsonString = JSONObject.toJSONString(myMessage);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("queryStr", jsonString);

        HttpUtil.getInstance().setGetRequest("获取中...", this, Constant.WEB_ROOT + Constant.MYNEWS, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    plv_message.onRefreshComplete();

                    MyMessageResult myMessageResult = JSONObject.parseObject(str, MyMessageResult.class);

                    if (Constant.STATUS_SUCESS.equals(myMessageResult.status)) {

                        setListView(myMessageResult.result);
                        mAdapter.setMyMessaglList(myMessaglList);
                        mAdapter.notifyDataSetChanged();

                    } else {
                        showToast(myMessageResult.message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("获取消息失败");
                }

            }

        }, new HttpUtil.FailListener() {
            @Override
            public void setOnFailListener() {
                plv_message.onRefreshComplete();
            }
        });

    }

    /**
     * 判断是否有重复并更新
     */
    private void setListView(List<MyMessageResult.MyMessageDetail> tempGuideLists) {

        if (tempGuideLists == null || tempGuideLists.size() == 0)
            return;

        if (myMessaglList.size() == 0) {

            myMessaglList.addAll(tempGuideLists);
            return;
        }

        for (MyMessageResult.MyMessageDetail goods : tempGuideLists) {
            boolean exist = false;
            for (MyMessageResult.MyMessageDetail g : myMessaglList) {
                if (goods.id_.equals(g.id_)) {
                    exist = true;
                    break;
                }
            }
            if (!exist)
                myMessaglList.add(goods);
        }

    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:

                finish();

                break;
        }

    }
}
